import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
import https from 'https'
import fs from 'fs'

// 定义后端服务地址变量
const backend = 'https://117.50.180.247:8010'

export default defineConfig({
  plugins: [vue()],
  server: {
    host: '0.0.0.0',
    port: 3000,
    https: {
      // 使用项目根目录下ssl目录中的证书
      key: fs.readFileSync(path.join(__dirname, './ssl/private.key')),
      cert: fs.readFileSync(path.join(__dirname, './ssl/certificate.crt')),
      // 添加更多加密算法支持以增强兼容性
      minVersion: 'TLSv1.2',
      ciphers: 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA256:AES128-GCM-SHA256:AES256-GCM-SHA384'
    },
    proxy: {
      '/api': {
        target: backend,
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src')
    }
  },
  build: {
    outDir: './web/dist',
    assetsDir: 'assets',
    sourcemap: false,
    rollupOptions: {
      input: {
        main: path.resolve(__dirname, 'index.html')
      }
    }
  },
  // 将src/config目录下的所有配置项集成到Vite配置中
  define: {
    // API配置
    'process.env.API_CONFIG': JSON.stringify({
      baseUrl: backend,
      endpoints: {
        record: '/record',
        human: '/human',
        offer: '/offer',
        downloadRecording: '/download_recording'
      },
      // 修改getUrl函数实现，使其不依赖this上下文
      getUrl: `function(endpoint) { const baseUrl = "${backend}"; const endpoints = { record: "/record", human: "/human", offer: "/offer", downloadRecording: "/download_recording" }; if (endpoints[endpoint]) { return baseUrl + endpoints[endpoint]; } console.error("API端点不存在:", endpoint); return ""; }`
    }),
    // 声音检测配置
    'process.env.AUDIO_CONFIG': JSON.stringify({
      SOUND_THRESHOLD: 0.05,
      CHECK_INTERVAL_MS: 100,
      SILENCE_TIMEOUT_MS: 1500
    }),
    // 视频配置
    'process.env.VIDEO_CONFIG': JSON.stringify({
      DEFAULT_SIZE_PERCENTAGE: 100,
      MIN_SIZE_PERCENTAGE: 50,
      MAX_SIZE_PERCENTAGE: 150
    }),
    // 会话配置
    'process.env.SESSION_CONFIG': JSON.stringify({
      DEFAULT_SESSION_ID: '0',
      CONNECTION_CHECK_INTERVAL_MS: 5000,
      WEBRTC_STATE_CHECK_INTERVAL_MS: 2000,
      WEBRTC_CONNECTION_TIMEOUT_MS: 60000
    }),
    // WebRTC配置
    'process.env.WEBRTC_CONFIG': JSON.stringify({
      sdpSemantics: 'unified-plan',
      // RTC客户端配置
      RtcClient: {
        turn_config: {
          turn_provider: "turn_server",
          urls: ["turn:117.50.180.247:3478", "turns:117.50.180.247:5349"],
          username: "username",
          credential: "password"
        }
      }
    })
  }
})